/**
 * 
 */
package info.sswap.ontologies.modularity.repo.rdf;

import info.sswap.ontologies.modularity.Module;
import info.sswap.ontologies.modularity.ModuleExtractionException;
import info.sswap.ontologies.modularity.ModuleExtractor;
import info.sswap.ontologies.modularity.owlapi.OWLAPIModule;

import java.net.URI;
import java.util.Collection;
import java.util.Set;

import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;

import uk.ac.manchester.cs.owlapi.modularity.ModuleType;
import edu.arizona.bio5.onto.decomposition.AtomicDecomposition;
import edu.arizona.bio5.onto.decomposition.persistent.PersistentAtomicDecomposition;
import edu.arizona.bio5.onto.modularity.SeedSigBasedModuleExtractor;
import edu.arizona.bio5.onto.modularity.Signature;

/**
 * @author Pavel Klinov
 *
 */
public class ADModuleExtractor implements ModuleExtractor {

	private final PersistentAtomicDecomposition mAD;
	
	public ADModuleExtractor(PersistentAtomicDecomposition ad) {
		mAD = ad;
	}	
	
	public ModuleType getModuleType() {
		return mAD == null ? null : mAD.getModuleType();
	}

	@Override
	public Module extract(Collection<URI> theSignature)	throws ModuleExtractionException {
		SeedSigBasedModuleExtractor extractor = new SeedSigBasedModuleExtractor();
		OWLOntologyManager mgr = OWLManager.createOWLOntologyManager();

		extractor.setDecomposition((AtomicDecomposition)mAD);	
		
		System.out.println("AD-based ME: extracting " + mAD.getModuleType() + " module for " + theSignature + " from the AD for " + mAD.getOntologyURI());
		
		try {
			Set<OWLAxiom> extractedAxioms = extractor.extract(new Signature(theSignature.toArray(new URI[]{})), true);
			//Filter out all annotations other than rdfs:isDefinedBy
			/*for (Iterator<OWLAxiom> iter = extractedAxioms.iterator(); iter.hasNext();) {
				OWLAxiom axiom = iter.next();
				
				if (axiom.isAnnotationAxiom() && 
						!((OWLAnnotationAssertionAxiom)axiom).getAnnotation().getProperty().getIRI().equals(OWLRDFVocabulary.RDFS_IS_DEFINED_BY.getIRI())) {
					iter.remove();
				}
			}*/
			
			System.out.println("Extracted " + extractedAxioms.size() + " axioms");
			
			return new OWLAPIModule(mgr.createOntology(extractedAxioms));
		} catch (OWLOntologyCreationException e) {
			throw new ModuleExtractionException(e);
		}
	}
}